/*
 * ADCC1.c
 *
 *  Created on: 15/01/2013
 *      Author: RIchard
 */

#include <msp430.h>
#include <string.h>
#include "ADCC1.h"
#include "../DIO/DIOC1.h"
#include "../DMA/DMAC1.h"

typedef struct
{
      uint8 u8Channel;
      uint8 u8Reference;
} ADC__tstADCChannelSetup;

static const ADC__tstADCChannelSetup   ADC__stADCChannelSetup[ ADC_nenNumberOfChannels ] =
{
/* ADC_nenPressure   */ { ADC12INCH_0, ADC12SREF_0 },
/* ADC_nenLight      */ { ADC12INCH_1, ADC12SREF_0 }
};

static DMA_tstTransfer ADC__stDMATransfer;

void ADC_vReset( void )
{
   memset( (void*)&ADC__stDMATransfer, 0, sizeof(ADC__stDMATransfer) );

   REFCTL0 = REFTCOFF;

   /* Turn ADC ON */
   /* Multiple sample and conversions */
   /* 1024 ADC12CLK cycles */
   ADC12CTL0 = ADC12MSC + ADC12SHT0_15;

   /* ASC12CLK = SMCLK */
   /* SAMPCON = Sampling Timer */
   /* ADC12DIV = Divide by 8 */
   /* Repeat single channel */
	ADC12CTL1 = ADC12SHP + ADC12DIV_7 + ADC12SSEL_3 + ADC12CONSEQ_2;

	/* 12bit */
	/* Temp sensor OFF */
	ADC12CTL2 = ADC12PDIV + ADC12RES_2 + ADC12TCOFF + ADC12SR;
}

void ADC_vReadRequest( ADC_tstRequest *stRequest )
{
   ADC12MCTL0  = ADC__stADCChannelSetup[ stRequest->enChannel ].u8Channel;
   ADC12MCTL0 |= ADC__stADCChannelSetup[ stRequest->enChannel ].u8Reference;

   ADC__stDMATransfer.enChannel = ADC_nDMAChannel;
   ADC__stDMATransfer.pu16Source = (vuint16*)&ADC12MEM0;
   ADC__stDMATransfer.u16Samples = stRequest->u8Samples;
   ADC__stDMATransfer.pu16Destination = stRequest->pu16DestBuffer;
   ADC__stDMATransfer.pfFinishCallback = stRequest->pfOKCallback;

   DMA_vStartTransfer( &ADC__stDMATransfer );

   ADC12CTL0 |= ADC12ON + ADC12ENC + ADC12SC;   /* move ADC12SC to init */

   /* TEST */
   MSP430_FAST_SET_PIN_TEST;
}

void ADC_vStopSampling( void )
{
   /* turn off the ADC module */
   ADC12CTL0 &= ~( ADC12ENC );
   ADC12CTL0 &= ~( ADC12ON );
}
